<template>
  <el-dialog v-model="visible" :title="!dataForm.tenantId ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-form-item label="套餐名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="套餐名称"></el-input>
      </el-form-item>
      <el-form-item label="套餐价格" prop="price">
        <el-input v-model="dataForm.price" placeholder="套餐价格"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="isActive">
        <ren-radio-group v-model="dataForm.isActive" dict-type="is_active"></ren-radio-group>
      </el-form-item>
      <el-form-item label="分类" prop="categoryName">
        <el-popover :width="400" ref="categoriesListPopover" placement="bottom-start" trigger="click" popper-class="popover-pop">
          <template v-slot:reference>
            <el-input v-model="dataForm.categoryName" :readonly="true" placeholder="上级分类">
              <template v-slot:suffix>
                <el-icon @click.stop="deptListTreeSetDefaultHandle()" class="el-input__icon"><circle-close /></el-icon>
              </template> </el-input>
          </template>
          <div class="popover-pop-body"><el-tree :data="categoriesList" :props="{ label: 'name', children: 'children' }" node-key="id" ref="categoriesTree" :highlight-current="true" :expand-on-click-node="false" accordion @current-change="deptListTreeCurrentChangeHandle"> </el-tree></div>
        </el-popover>
      </el-form-item>
      <el-form-item label="套餐大图片" prop="imageUrl">
        <images ref="imagesRef" @refreshDataList="refreshDataListHandle" />
      </el-form-item>
      <el-form-item label="菜品缩略图" prop="imageUrl">
        <images ref="thumimagesRef" @refreshDataList="refreshThumbnailListsHandle" />
      </el-form-item>
      <el-form-item label="就餐类型" prop="eatType">
        <ren-select :multiple="true" v-model="dataForm.eatType" dict-type="eat_type" placeholder="就餐类型"></ren-select>
          <!-- <el-select v-model="dataForm.eatType" :multiple="true" placeholder="就餐类型" clearable>
            <el-option :key="data.dictValue" :value="data.dictValue" :label="data.dictLabel" v-for="data in getDictDataList(store.state.dicts, 'eat_type')">{{ data.dictLabel }}</el-option>
          </el-select> -->
      </el-form-item>
      <el-form-item label="选择菜品" prop="dishIds">
        <el-transfer
          :titles="['未选菜品', '已选菜品']"
          filterable
          :filter-method="filterMethod"
          filter-placeholder="请输入菜单名"
          v-model="dataForm.dishIds"
          :data="dishLists">
        </el-transfer>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import Images from "./images.vue";
import { ElMessage } from "element-plus";
import { useAppStore } from "@/store";
import { getDictDataList } from "@/utils/utils";
const store = useAppStore();
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);
const categoriesListPopover = ref();
const visible = ref(false);
const dataFormRef = ref();
const categoriesList = ref();
const dishLists:any = ref([]);

const imagesRef = ref();
const thumimagesRef = ref();

const rules = ref({
  name: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  price: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  isActive: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  categoryName: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  eatType: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  dishIds: [{ required: true, message: t("validate.required"), trigger: "blur" }],
});

const dataForm = reactive({
  id: "",
  tenantId: "",
  storeId: "",
  name: "",
  eatType: [],
  price: "",
  isActive: "",
  categoryId: null,
  categoryName: null,
  creator: "",
  updator: "",
  createDate: "",
  updateDate: "",
  dishIds: [],
  imageUrl: "",
  imageLists: [],
  thumbnailLists: [],

});



const filterMethod = (query:any, item:any) => {
  return item.label.indexOf(query) > -1;
}

// 获取分类列表
const getCategoriesList = () => {
  return baseService.get("/sys/zycategories/list").then((res:any) => {
    if (res.code !== 200) {
      return ElMessage.error(res.msg);
    }
    categoriesList.value = res.data;
  });
};

const getDishList = () => {
  baseService.get("/sys/dishes/list", {}).then((res:any) => {
    if (res.code !== 200) {
      return ElMessage.error(res.msg);
    }
    dishLists.value = res.data.map((item:any) => {
      return {label: item.name, key: item.dishId}
    });
  });
};

const deptListTreeSetDefaultHandle = () => {
  dataForm.categoryId = null;
  dataForm.categoryName = null;
};

// 上级部门树, 选中
const deptListTreeCurrentChangeHandle = (data: any) => {
  dataForm.categoryId = data.id;
  dataForm.categoryName = data.name;

  categoriesListPopover.value.hide();
};


const refreshDataListHandle = (imageLists:any) => {
  dataForm["imageLists"] = imageLists;
};
const refreshThumbnailListsHandle = (thumLists:any) => {
  dataForm["thumbnailLists"] = thumLists;
};

const init = async (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  getDishList();
  getCategoriesList();

  if (id) {
    const res = await baseService.get("/sys/setmeals/" + id);
    const aa = {eatType: res.data?.eatType ? (res.data?.eatType as string).split(","): []}
    Object.assign(dataForm, res.data, aa);
  }
  // 必须的否则上传图片异常
  nextTick(() => {
    imagesRef.value.init(dataForm.id, 1, dataForm.imageLists);
    thumimagesRef.value.init(dataForm.id, 6, dataForm.thumbnailLists);
  });
};


// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.tenantId ? baseService.post : baseService.put)("/sys/setmeals", Object.assign(dataForm, {eatType: dataForm.eatType.join(",")})).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
